package manager;

import java.io.IOException;
import java.util.ArrayList;

import javax.swing.JLabel;
import javax.swing.JTextField;

import manager.interfaces.IMenuAdder;
import manager.interfaces.IMenuManager;
import util.FileIOHelper;
import view.panel.SubMenuPanel;
import vo.Menu;
import exception.NotFoundException;

public class MenuManager implements IMenuManager {

	private static MenuManager menuManager = new MenuManager();
	public ArrayList<Menu> menuList;
		
	private MenuManager() {
		menuList = new ArrayList<Menu>();
	}

	public static MenuManager getInstance() {

		if(null == menuManager) {
			return new MenuManager();
		} else {
			return menuManager;
		}	

	}

	@Override
	public void saveMenu(Menu menu) throws IOException {
		menuList.add(menu);
	
			
		saveMenuToFile();
	}
	
	private void saveMenuToFile() throws IOException {
	
		FileIOHelper fileIO = new FileIOHelper();
		final String tab = "    ";
		StringBuffer sb = new StringBuffer();

		for(int i = 0; i < menuList.size(); ++i) {
			// 메뉴 리스트에서
			Menu menu = menuList.get(i);
			// 형식에 맞추어 출력
			sb.append("메뉴 : " + menu.getName() +  tab + 
					"가격 : " + menu.getPrice() + "\n"); 

		}
		// 파일에 쓰기
		fileIO.writeFile("menu.txt", sb.toString());
		
	}

	@Override
	public boolean deleteMenu(String menuName) throws NotFoundException {

		for(int i = 0; i < menuList.size(); ++i) {

			Menu menu = menuList.get(i);

			// 사용자가 입력한 이름으로 메뉴 리스트에서 검색
			if(menuName.equals(menu.getName())) {
				menuList.remove(i);
				return true;
			}			
		}

		return false;
	}

	@Override
	public int analzeMenu(String menuName) throws NotFoundException {

		int salesCount = 0, price = 0;
		Menu seekedMenu = null;

		for(int i = 0; i < menuList.size(); ++i) {

			Menu menu = menuList.get(i);

			if(menuName.equals(menu.getName())) {
				seekedMenu = menu;	
				price = seekedMenu.getPrice();
				break;
			}

		}

		// 찾는 메뉴가 없는 경우 익셉션 처리
		if(null == seekedMenu) {
			throw new NotFoundException();
		}
		
		salesCount = OrderManager.getInstance().getOrderedMenuCount(menuName);

		return price * salesCount;
	}

	@Override
	public Menu searchMenu(String menuName) throws NotFoundException {

		Menu seekedMenu = null;

		for(int i = 0; i < menuList.size(); ++i) {

			Menu menu = menuList.get(i);

			// 사용자가 입력한 이름으로 메뉴 리스트에서 검색
			if(menuName.equals(menu.getName())) {
				seekedMenu = menu;
				break;
			}			
		}

		// 찾는 메뉴가 없는 경우 익셉션 처리
		if(null == seekedMenu) {
			throw new NotFoundException();
		}

		return seekedMenu;
	}

}
